package videobuy

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
)

// GetBuyList 获取视频购买列表
func (b *sVideoBuy) GetBuyList(ctx context.Context, in model.VideoBuyListInput) (out *model.VideoBuyListOutput, err error) {
	out = &model.VideoBuyListOutput{}
	// 用户端
	if in.FormSide == enums.FormSideBus {
		in.Uid = service.BizCtx().GetUid(ctx)
	}

	// 获取数据
	err = b.BuyModel().ListAndTotal(ctx, model.CommonListAndTotalInput{
		CommonPaginationItem: in.CommonPaginationItem,
		Where:                b.VideoBuyWhere(ctx, in.VideoBuyWhereItem),
		Sort:                 fmt.Sprintf(`%s desc`, dao.VideoBuy.Columns().Id),
	}, &out.Rows, &out.Total)
	return
}

// GetVideoBuyAuthDetail 获取用户购买视频授权信息
func (b *sVideoBuy) GetVideoBuyAuthDetail(ctx context.Context, videoId uint) (detail *model.VideoBuyAuthItem, err error) {
	detail = &model.VideoBuyAuthItem{}
	// 获取视频购买授权详情
	err = b.BuyModel().Scan(ctx, g.Map{
		dao.VideoBuy.Columns().VideoId: videoId,
		dao.VideoBuy.Columns().Uid:     service.BizCtx().GetUid(ctx),
	}, &detail)
	if err != nil {
		return nil, exception.New(`该用户暂无视频购买信息`)
	}

	// 购买集数
	detail.BuyEpisodesResult = b.BuyEpisodesAuthResult(ctx, videoId)
	return
}

// GetBuyDetail 获取视频购买详情
func (b *sVideoBuy) GetBuyDetail(ctx context.Context, buyId uint) (out *model.VideoBuyDetailOutput, err error) {
	out = &model.VideoBuyDetailOutput{}
	// 获取购买详情
	err = b.BuyModel().Scan(ctx, g.Map{
		dao.VideoBuy.Columns().Id: buyId,
	}, &out.VideoBuyDetailItem)
	if err != nil {
		return nil, err
	}

	// 获取账单列表
	out.BillList, err = b.GetBillList(ctx, model.VideoBuyBillListWhere{
		BuyId: buyId,
	})
	return
}
